import { Component } from 'react';
import React from 'react';
import { Tag } from 'antd';

interface KeywordFilterSearchProps {
  filters: Array<FilterKeywords>;
}

interface FilterKeywords {
  title: string;
  multiple?: boolean;
  keywords: Array<string>;
}
interface KeywordFilterSearchState {
  selected: { values?: Array<string>; [key: string]: Array<string> | undefined };
}
class KeywordFilterSearch extends Component<KeywordFilterSearchProps, KeywordFilterSearchState> {
  constructor(props: any) {
    super(props);
    this.state = { selected: {} };
  }
  render() {
    const CheckableTag = Tag.CheckableTag;

    return (
      <div>
        {this.props.filters.map((item, index) => {
          return (
            <div
              key={index}
              style={{
                margin: `12px 12px ${index + 1 == this.props.filters.length ? '12px' : '0px'}`,
              }}
            >
              <span style={{marginRight:"12px"}}>{item.title}</span>
              {item.keywords.map((tag) => {
                const newLocal = this.state.selected[item.title]?.indexOf(tag);
                return (                                                                                    
                  <CheckableTag
                    key={tag}
                    checked={newLocal != undefined ? newLocal >= 0 : false}
                    onChange={(checked) => this.handleChange(item, tag, checked)}
                  >
                    {tag}
                  </CheckableTag>
                );
              })}
            </div>
          );
        })}
      </div>
    );
  }
  handleChange(filter: FilterKeywords, tag: string, checked: boolean): void {
    const { selected } = this.state;
    const current = (selected[filter.title] ? selected[filter.title] : []) as [];
    const nextSelectedTags = filter.multiple
      ? checked
        ? [...current, tag]
        : current?.filter((t) => t !== tag)
      : checked
      ? [tag]
      : [];
    const newSelect = { ...selected };
    newSelect[filter.title] = nextSelectedTags;
    console.log('You are interested in: ', nextSelectedTags);
    this.setState({ selected: newSelect });
  }
}

export default KeywordFilterSearch;
